package cn.yhp.chatgpt.data.trigger.http;

import cn.yhp.chatgpt.data.domain.weixin.model.entity.MessageTextEntity;
import cn.yhp.chatgpt.data.domain.weixin.model.entity.UserBehaviorMessageEntity;
import cn.yhp.chatgpt.data.domain.weixin.service.IWeiXinBehaviorService;
import cn.yhp.chatgpt.data.domain.weixin.service.IWeiXinValidateService;
import cn.yhp.chatgpt.data.types.sdk.weixin.XmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 微信公众号，消息处理服务，验签和请求应答
 * @author yhp
 * @description
 * @date 2024/2/4
 */
@RestController
@RequestMapping("/api/${app.config.api-version}/wx/portal/{appid}")
@Slf4j
public class WeiXinPortalController {

    @Resource
    private IWeiXinValidateService weiXinValidateService;

    @Resource
    private IWeiXinBehaviorService weiXinBehaviorService;

    /**
     * 处理微信服务器发来的get请求，进行签名的验证（在公众号的基本配置/填写服务器下面url配置会验证）
     * 如：http://28d61792.r11.cpolar.top/wx/portal/xx
     *
     * @param appid     微信端AppID
     * @param signature 微信端发来的签名
     * @param timestamp 微信端发来的时间戳
     * @param nonce     微信端发来的随机字符串
     * @param echostr   微信端发来的验证字符串
     * @return
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String validate(@PathVariable String appid, @RequestParam String signature,
                           @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        try {
            log.info("微信公众号验签信息[appid]{}开始 [signature:{}, timestamp:{}, nonce:{}, echostr:{}]", appid, signature, timestamp, nonce, echostr);
            if (weiXinValidateService.checkSign(signature, timestamp, nonce,echostr)) {
                return echostr;
            }
            return null;
        } catch (Exception e) {
            log.error("微信公众号验签失败", e);
            return null;
        }
    }


    // 处理微信客户端转发的消息(AppID 是开发者与微信开放平台进行通信和授权验证的标识；OpenID 是用户在公众号中的唯一标识；OriginalID 是公众号的全局唯一标识符)
    @PostMapping(produces = "application/xml;charset=utf-8")//返回的内容格式
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.info("接收微信消息：appid:{},消息[xml格式]：{}", appid, requestBody);
        MessageTextEntity message = XmlUtil.xmlToBean(requestBody, MessageTextEntity.class);

        // 构建消息参数（像重新复制了份MessageTextEntity，只取需要的信息字段）
        UserBehaviorMessageEntity entity = UserBehaviorMessageEntity.builder()
                .openId(openid)
                .fromUserName(message.getFromUserName())
                .msgType(message.getMsgType())
                .content(message.getContent())
                .event(message.getEvent())
                .createTime(new Date(Long.parseLong(message.getCreateTime()) * 1000L))
                .build();
        // 消息处理
        return weiXinBehaviorService.acceptUserBehavior(entity);
    }
}
